import { getBcmDictItem } from '../../../hooks/bcmUseUntils';
import esc from "@/common/printer/esc";
import BluetoothPrinter from '../../../common/BluetoothPrinter';
import { useMainStore } from '@/store/modules/store';
import { usePrinterStore } from "@/store/printerStore";
import { storeToRefs } from 'pinia'

/**
 * EMOJI字符正则
 * @type {RegExp}
 */
const emojiRegex = /[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n]/g //表情的正则匹配
let command;
const DEFAULT_FONT_SIZE = 0; // 默认字体
const MEDIUM_FONT_SIZE = 1; //中号字体
const LARGE_FONT_SIZE = 17; //大号字体
const DEFAULT_ROW_SPACE = 60; //默认行间距
const MEDIUM_ROW_SPACE = 80;
const LARGE_ROW_SPACE = 100;
const ERROR_MESSAGE = {
    0: '正常',
    10000: '未初始化蓝牙适配器',
    10001: '当前蓝牙适配器不可用',
    10002: '没有找到指定设备',
    10003: '连接失败',
    10004: '没有找到指定服务',
    10005: '没有找到指定特征值',
    10006: '当前连接已断开',
    10007: '当前特征值不支持此操作',
    10008: '其余所有系统上报的异常',
    10009: 'Android 系统特有，系统版本低于 4.3 不支持 BLE',
    10010: '已连接',
    10011: '配对设备需要配对码',
    10012: '连接超时',
    10013: '为空或者是格式不正确',
};

const generateArray = function (num) {
    let resultArray = [];
    for (let i = 0; i < num; i++) {
        resultArray.push(1);
    }
    return resultArray;
}

const getPrintData = function (data, type = 'order', printTimes) {
    command = esc.createNew();
    command.init()
    if (['order', 'orderCancelApply', 'orderRefundApply','afs'].includes(type)) {
        if (printTimes?.customerReceipt) {
            generateArray(printTimes?.customerReceipt)?.map(v => {
                return type === "order" ? getOrderFormatCmd(data, '顾客联') : getAfsOrderFormatCmd(data, '顾客联')
            })
        }
        if (printTimes?.pickupReceipt) {
            generateArray(printTimes?.pickupReceipt)?.map(v => {
                return type === "order" ? getOrderFormatCmd(data, '拣货联') : null;
            })
        }
        if (printTimes?.merchantReceipt) {
            generateArray(printTimes?.merchantReceipt)?.map(v => {
                return type === "order" ? getOrderFormatCmd(data, '商家联') : getAfsOrderFormatCmd(data, '商家联');
            })
        }
    } else if (type === 'pickTask') {
        getPickTaskFormatCmd(data, null)
    } else if (['orderCancelApplyRepeal', 'orderCanceled', 'orderRefundCanceled', 'orderRefundApplyRepeal'].includes(type)) {
        printAfsOrderCancelFormatCmd(data, type)
    }
    return command.getData();
}

/**
 * 获取订单打印指令
 * @param bcmOrder 订单对象
 * @param type 打印联类型：顾客联、商家联
 * @returns {object}
 */
const getOrderFormatCmd = function (bcmOrder, type) {
    const printerStore = usePrinterStore();
    const { orderGoodsPrintSortType } = storeToRefs(printerStore);
    command.bold(1); //加粗
    command.setFontSize(MEDIUM_FONT_SIZE);
    command.setSelectJustification(0)//居左

    command.setText((type ? type : '顾客联') + (bcmOrder?.printTimes > 0 ? "（重印" + bcmOrder?.printTimes + '）' : ''));
    command.setPrint();

    command.bold(0);
    command.setFontSize(DEFAULT_FONT_SIZE);
    command.setSelectJustification(1)
    command.setText(bcmOrder?.pickType === '0' ? '【配送订单】' : bcmOrder?.pickType === '1' ? '【自提订单】' : '【邮寄订单】');
    command.setPrint();

    command.setSelectJustification(0)
    const chnlName = getBcmDictItem('chnlType', bcmOrder?.chnlType).text;
    command.setFontSize(LARGE_FONT_SIZE);
    command.bold(1); //加粗
    command.setSelectJustification(1)//居中
    command.setText(chnlName + (!!bcmOrder?.thirdOrderIndex ? '#' + bcmOrder?.thirdOrderIndex : ''));
    command.setPrint();
    command.bold(0);
    command.setFontSize(DEFAULT_FONT_SIZE);
    command.setSelectJustification(0)//居左

    command.setText('--------------------------------');
    command.setPrint();

    command.setText('门店名称：' + bcmOrder.storeName);
    command.setPrint();

    command.setText((bcmOrder.pickType != '1' ? '预计送达：' : '预计自提：') + bcmOrder.expectDeliveryTime);
    command.setPrint();

    command.setText('下单时间：' + bcmOrder.orderCreateTime);
    command.setPrint();

    command.setText('订单号：' + bcmOrder.thirdOrderNo);
    command.setPrint();

    let buyerRemark = bcmOrder.buyerRemark;
    if (emojiRegex.test(buyerRemark)) {
        buyerRemark = bcmOrder.buyerRemark.replace(emojiRegex, '')
    }

    command.bold(1);
    command.setFontSize(MEDIUM_FONT_SIZE);
    command.setText('备注：' + buyerRemark);
    command.setPrint();
    command.bold(0);
    command.setFontSize(DEFAULT_FONT_SIZE);

    command.setText('--------------------------------');
    command.setPrint();

    if (type == '顾客联' && bcmOrder?.isEvreceipt == '1') {
        command.setSelectErrorCorrectionLevelForQRCode(51);
        command.setStoreQRCodeData(bcmOrder?.evreceiptUrl);
        command.setSelectJustification(1); //居中
        command.setSelectSizeOfModuleForQRCode(8); //大小
        command.setPrintQRCode();
        command.setPrint();
        command.setSelectJustification(1)//居中
        command.setText('扫码查看订单商品明细');
        command.setPrint();

    } else {
        // todo xiaoch  需要分列打印
        command.setText('商品名称  单价   金额    数量');
        command.setPrint();

        command.setText('--------------------------------');
        command.setPrint();

        let goodsList = bcmOrder.bcmOrderGoodsList;
        if (type == '顾客联') {
            goodsList = orderGoodsPrintSortType.customerReceipt == 1 ? goodsList : goodsList.sort((a, b) => a?.erpCateCode - b?.erpCateCode)
        }
        if (type == '拣货联') {
            goodsList = orderGoodsPrintSortType.pickupReceipt == 1 ? goodsList : goodsList.sort((a, b) => a?.erpCateCode - b?.erpCateCode)
        }
        if (type == '商家联') {
            goodsList = orderGoodsPrintSortType.merchantReceipt == 1 ? goodsList : goodsList.sort((a, b) => a?.erpCateCode - b?.erpCateCode)
        }

        goodsList?.map((goods, index) => {
            let goodsName = goods.goodsName;
            if (emojiRegex.test(goodsName)) {
                goodsName = goods.goodsName.replace(emojiRegex, '')
            }
            command.bold(1);
            command.setFontSize(MEDIUM_FONT_SIZE);
            command.setText((index + 1) + '.' + goodsName);
            command.setPrint();

            let goodsRow = goods.storePrice.toFixed(2) + '  ' + (goods.storePrice * goods.goodsNum).toFixed(2) + '     X' + goods.goodsNum;

            command.setSelectJustification(2);   //居右
            command.setText(goodsRow);
            command.setPrint();
            command.bold(0);
            command.setFontSize(DEFAULT_FONT_SIZE);
            command.setSelectJustification(0); //局左

            if (bcmOrder.chnlType != 'jddj' && typeof (goods.actualPrice) == 'number' && goods.actualPrice != goods.storePrice && goods.storePrice - goods.actualPrice > 0) {
                command.bold(1);
                command.setText('促销价：' + goods.actualPrice?.toFixed(2));
                command.setPrint();
            }
            command.bold(0);
            if (goods.isFreshGoods == '1') {
                command.setText('商品重量：' + goods.weightForUnit * 1000 + 'g');
                command.setPrint();
            }

            command.setText('商品编码：' + goods.goodsCode);
            command.setPrint();

            command.setText('商品条码：' + goods.goodsBarcode);
            command.setPrint();

            if (goods.refundGoodsNum > 0) {
                command.setText(`【已退${goods.isFreshGoods == '1' ? parseInt(String(goods.refundGoodsNum * goods.weightForUnit * 1000)) + 'g' : goods.refundGoodsNum + '件'}】`);
                command.bold(1);
                command.setPrint();
            }
        })
    }
    command.bold(0);
    command.setText('--------------------------------');
    command.setPrint();

    command.setSelectJustification(2)
    command.setText('商品总件数：' + bcmOrder.orderGoodsNum);
    command.setPrint();

    if (bcmOrder.chnlType !== 'jddj') {
        if (bcmOrder.originalPrice > 0) {
            command.setText('商品原价总额：￥' + bcmOrder.originalPrice.toFixed(2));
            command.setPrint();
        }
    } else {
        if (bcmOrder.goodsLevelDiscountAmount > 0) {
            command.setText('商品金额：￥' + bcmOrder.goodsLevelDiscountAmount.toFixed(2));
            command.setPrint();
        }
    }
    if (bcmOrder.pickType === '1') {
        if (bcmOrder.selfPickPayAmount > 0) {
            command.setText('自提服务费：￥' + bcmOrder.selfPickPayAmount.toFixed(2));
            command.setPrint();
        }
    }
    if (bcmOrder.lunchBoxAmount > 0) {
        command.setText('餐盒费：￥' + bcmOrder.lunchBoxAmount.toFixed(2));
        command.setPrint();
    }
    command.setText('包装费：￥' + bcmOrder.packageAmount.toFixed(2));
    command.setPrint();


    if (bcmOrder.pickType != '1') {
        if (bcmOrder.chnlType != 'homemall') {
            command.setText('配送费：￥' + (bcmOrder?.deliveryAmount > 0 ? bcmOrder?.deliveryAmount.toFixed(2) : '0.00'));
            command.setPrint();
        } else {
            command.setText('基础配送费：￥' + (bcmOrder?.baseDeliveryAmount > 0 ? bcmOrder?.baseDeliveryAmount.toFixed(2) : '0.00'));
            command.setPrint();

            if (bcmOrder?.overWeightDeliveryAmount > 0) {
                command.setText('超重配送费：￥' + bcmOrder.overWeightDeliveryAmount.toFixed(2));
                command.setPrint();
            }

            if (bcmOrder?.overDistanceDeliveryAmount > 0) {
                command.setText('超远配送费：￥' + bcmOrder.overDistanceDeliveryAmount.toFixed(2));
                command.setPrint();
            }
        }
    }

    if (bcmOrder?.platformPointsAmount > 0) {
        command.setText('平台积分抵扣：-￥' + bcmOrder.platformPointsAmount.toFixed(2));
        command.setPrint();
    }

    if (bcmOrder?.lunchBoxDiscount > 0) {
        command.setText('餐盒费优惠：-￥' + bcmOrder.lunchBoxDiscount.toFixed(2));
        command.setPrint();
    }

    if (bcmOrder?.packageDiscount > 0) {
        command.setText('包装费优惠：-￥' + bcmOrder.packageDiscount.toFixed(2));
        command.setPrint();
    }

    if (bcmOrder?.deliveryDiscount > 0) {
        command.setText('配送费优惠：-￥' + bcmOrder.deliveryDiscount.toFixed(2));
        command.setPrint();
    }

    if (bcmOrder.chnlType !== 'jddj') {
        if (bcmOrder.totalDiscountAmount > 0) {
            command.setText('订单优惠：-￥' + bcmOrder.totalDiscountAmount.toFixed(2));
            command.setPrint();
        }
    } else {
        if (bcmOrder.orderLevelDiscount > 0) {
            command.setText('商品优惠：-￥' + bcmOrder.orderLevelDiscount.toFixed(2));
            command.setPrint();
        }
    }
    if (bcmOrder.pickType === '1') {
        if (bcmOrder.selfPickDiscountAmount > 0) {
            command.setText('自提服务费优惠：￥' + bcmOrder.selfPickDiscountAmount.toFixed(2));
            command.setPrint();
        }
    }

    command.setText('--------------------------------');
    command.setPrint();

    if (bcmOrder.bcmOrderPayList?.length > 0) {
        bcmOrder.bcmOrderPayList?.map((pay, index) => {
            if (pay.payName) {
                command.setText(pay.payName + ':￥' + pay.amount.toFixed(2));
                command.setPrint();
            }
        })
    } else {
        command.setText('总件数：' + bcmOrder.orderGoodsNum + '      ' + '实付：￥' + bcmOrder.totalAmount.toFixed(2));
        command.setPrint();
    }
    command.setSelectJustification(0)
    command.setText('--------------------------------');
    command.setPrint();

    command.bold(1);
    command.setFontSize(MEDIUM_FONT_SIZE);
    command.setText(bcmOrder.consigneeName + '  ' + bcmOrder.consigneePhone);
    command.setPrint();

    let consigneeAddress = bcmOrder.consigneeAddress;
    if (emojiRegex.test(consigneeAddress)) {
        consigneeAddress = bcmOrder.consigneeAddress.replace(emojiRegex, '')
    }
    command.setText("地址：" + consigneeAddress);
    command.setPrint();
    command.setPrintAndFeedRow(1);

    command.bold(0);
    command.setFontSize(DEFAULT_FONT_SIZE);

    if (!type || type == '顾客联') {
        //打印二维码
        command.setSelectErrorCorrectionLevelForQRCode(51);
        command.setStoreQRCodeData(bcmOrder?.thirdOrderNo);
        command.setSelectJustification(1); //居中
        command.setSelectSizeOfModuleForQRCode(8); //大小
        command.setPrintQRCode();
        command.setPrint();
        command.setSelectJustification(1)//居中
        command.setText('订单号：' + bcmOrder.thirdOrderNo);
        command.setPrint();
    }

    command.setPrintAndFeedRow(2);

    command.setText('------------分割线-------------');
    command.setPrint();
    command.setPrintAndFeedRow(2);
    return command.getData();
}

const getPrintTitle = (type) => {
    switch (type) {
        case 'orderCancelApplyRepeal':
            return '订单取消申请已撤销';
        case 'orderCanceled':
            return '订单已取消';
        case 'orderRefundApplyRepeal':
            return '退款申请已撤销';
        case 'orderRefundCanceled':
            return '订单发起退款成功';
        default:
            return '';
    }
}

/**
 * 获取售后单打印指令
 * @param bcmAfsOrder 售后单对象
 * @param type 打印联类型：顾客联、商家联
 * @returns {string}
 */
const getAfsOrderFormatCmd = function (bcmAfsOrder, type) {
    command.bold(1); //加粗
    command.setFontSize(MEDIUM_FONT_SIZE);
    command.setSelectJustification(0);
    command.setText(type);
    command.setPrint();

    command.bold(0);
    command.setFontSize(MEDIUM_FONT_SIZE);
    command.setSelectJustification(1);
    command.setText('【售后单】');
    command.setPrint();

    command.setSelectJustification(0);
    const chnlName = getBcmDictItem('chnlType', bcmAfsOrder?.chnlType).text;
    command.setFontSize(LARGE_FONT_SIZE);
    command.bold(1); //加粗
    command.setSelectJustification(1)//居中
    command.setText(chnlName + (!!bcmAfsOrder?.thirdOrderIndex ? '#' + bcmAfsOrder?.thirdOrderIndex : ''));
    command.setPrint();
    command.bold(0);
    command.setFontSize(DEFAULT_FONT_SIZE);
    command.setSelectJustification(0)//居左

    command.setText('--------------------------------');
    command.setPrint();

    command.setText('门店名称：' + bcmAfsOrder?.storeName);
    command.setPrint();

    command.setText('期望上门时间：' + (bcmAfsOrder?.expectPickUpStartTime || '-'));
    command.setPrint();

    command.setText('发起时间：' + bcmAfsOrder?.sponsorTime);
    command.setPrint();

    command.setText('原订单号：' + bcmAfsOrder?.thirdOrderNo);
    command.setPrint();

    command.setText('售后单号：' + bcmAfsOrder?.thirdAfsOrderNo);
    command.setPrint();

    let afsReason = bcmAfsOrder?.afsReason;
    if (emojiRegex.test(bcmAfsOrder?.afsReason)) {
        afsReason = bcmAfsOrder?.afsReason.replace(emojiRegex, '')
    }
    command.bold(1);
    command.setFontSize(MEDIUM_FONT_SIZE);
    command.setText('原因：' + afsReason);
    command.setPrint();
    command.bold(0);
    command.setFontSize(DEFAULT_FONT_SIZE);

    command.setText('--------------------------------');
    command.setPrint();

    command.setText('商品名称  单价   金额    数量');
    command.setPrint();

    command.setText('--------------------------------');
    command.setPrint();

    bcmAfsOrder?.bcmAfsOrderGoodsList?.map((goods, index) => {
        if (emojiRegex.test(goods.goodsName)) {
            goods.goodsName = goods.goodsName.replace(emojiRegex, '')
        }
        command.bold(1);
        command.setFontSize(MEDIUM_FONT_SIZE);
        command.setText((index + 1) + '.' + goods.goodsName);
        command.setPrint();

        let goodsRow = goods.storePrice.toFixed(2) + '  ' + (goods.goodsPrice * goods.refundNum).toFixed(2) + '     X' + goods.refundNum;

        command.setSelectJustification(2)//居右
        command.setText(goodsRow);
        command.setPrint();
        command.bold(0);
        command.setSelectJustification(0)//局左
        command.setFontSize(DEFAULT_FONT_SIZE);

        if (bcmAfsOrder.chnlType != 'jddj' && typeof (goods.actualPrice) == 'number' && goods.actualPrice != goods.storePrice && goods.storePrice - goods.actualPrice > 0) {
            command.bold(1);
            command.setText('促销价：' + goods.actualPrice?.toFixed(2));
            command.setPrint();
        }
        command.bold(0);
        if (goods.isFreshGoods == '1') {
            command.setText('商品重量：' + goods.refundWeight * 1000 + 'g');
            command.setPrint();
        }
        command.setText('商品编码：' + goods.goodsCode);
        command.setPrint();

        command.setText('商品条码：' + goods.goodsBarcode);
        command.setPrint();

        if (goods.isFreshGoods == '1') {
            command.setText(`【已退 ${parseInt(String(goods.refundNum * goods.refundWeight * 1000))} g】`)
            command.bold(1);
            command.setPrint();
        }

    })
    command.bold(0);
    command.setText('--------------------------------');
    command.setPrint();

    command.setSelectJustification(2)
    command.setText('商品总件数：' + bcmAfsOrder.afsOrderGoodsNum);
    command.setPrint();

    if (bcmAfsOrder?.chnlType !== 'jddj') {
        if (bcmAfsOrder?.originalPrice > 0) {
            command.setText('商品原价总额：￥' + bcmAfsOrder?.originalPrice.toFixed(2));
            command.setPrint();
        }
    } else {
        if (bcmAfsOrder?.goodsLevelDiscountAmount > 0) {
            command.setText('商品金额：￥' + bcmAfsOrder?.goodsLevelDiscountAmount.toFixed(2));
            command.setPrint();
        }
    }

    if (bcmAfsOrder?.lunchBoxAmount > 0) {
        command.setText('餐盒费：￥' + bcmAfsOrder?.lunchBoxAmount.toFixed(2));
        command.setPrint();
    }
    command.setText('包装费：￥' + bcmAfsOrder?.packageAmount.toFixed(2));
    command.setPrint();

    if (bcmAfsOrder?.chnlType !== 'homemall') {
        command.setText('配送费：￥' + (bcmAfsOrder?.deliveryAmount > 0 ? bcmAfsOrder?.deliveryAmount.toFixed(2) : '0.00'));
        command.setPrint();
    } else {
        command.setText('基础配送费：￥' + (bcmAfsOrder?.baseDeliveryAmount > 0 ? bcmAfsOrder?.baseDeliveryAmount.toFixed(2) : '0.00'));
        command.setPrint();
        if (bcmAfsOrder?.overWeightDeliveryAmount > 0) {
            command.setText('超重配送费：￥' + bcmAfsOrder.overWeightDeliveryAmount.toFixed(2));
            command.setPrint();
        }

        if (bcmAfsOrder?.overDistanceDeliveryAmount > 0) {
            command.setText('超远配送费：￥' + bcmAfsOrder.overDistanceDeliveryAmount.toFixed(2));
            command.setPrint();
        }
    }

    if (bcmAfsOrder?.platformPointsAmount > 0) {
        command.setText('平台积分抵扣：-￥' + bcmAfsOrder?.platformPointsAmount.toFixed(2));
        command.setPrint();
    }

    if (bcmAfsOrder?.lunchBoxDiscount > 0) {
        command.setText('餐盒费优惠：-￥' + bcmAfsOrder?.lunchBoxDiscount.toFixed(2));
        command.setPrint();
    }

    if (bcmAfsOrder?.packageDiscount > 0) {
        command.setText('包装费优惠：-￥' + bcmAfsOrder?.packageDiscount.toFixed(2));
        command.setPrint();
    }

    if (bcmAfsOrder?.deliveryDiscount > 0) {
        command.setText('配送费优惠：-￥' + bcmAfsOrder?.deliveryDiscount.toFixed(2));
        command.setPrint();
    }

    if (bcmAfsOrder?.chnlType !== 'jddj') {
        if (bcmAfsOrder?.totalDiscountAmount > 0) {
            command.setText('订单优惠：-￥' + bcmAfsOrder?.totalDiscountAmount.toFixed(2));
            command.setPrint();
        }
    } else {
        if (bcmAfsOrder?.orderLevelDiscount > 0) {
            command.setText('商品优惠：-￥' + bcmAfsOrder?.orderLevelDiscount.toFixed(2));
            command.setPrint();
        }
    }

    if (bcmAfsOrder?.pickType === '1') {
        if (bcmAfsOrder?.selfPickDiscountAmount > 0) {
            command.setText('自提服务费优惠：-￥' + bcmAfsOrder?.selfPickDiscountAmount.toFixed(2));
            command.setPrint();
        }
    }

    command.setText('--------------------------------');
    command.setPrint();

    if (bcmAfsOrder?.bcmAfsOrderPayList?.length > 0) {
        bcmAfsOrder?.bcmAfsOrderPayList?.map((pay, index) => {
            if (pay.payName) {
                command.setText(pay.payName + ':￥' + pay.amount.toFixed(2));
                command.setPrint();
            }
        })
    } else {
        command.setText('总件数：' + bcmAfsOrder?.afsOrderGoodsNum + '      ' + '退款金额：' + bcmAfsOrder?.refundAmount.toFixed(2));
        command.setPrint();
    }
    command.setSelectJustification(0)
    command.setText('--------------------------------');
    command.setPrint();

    command.bold(1);
    command.setFontSize(MEDIUM_FONT_SIZE);
    command.setText(bcmAfsOrder?.contactName + '  ' + bcmAfsOrder?.privacyContactPhone);
    command.setPrint();

    let pickUpAddress = bcmAfsOrder?.pickUpAddress;
    if (emojiRegex.test(pickUpAddress)) {
        pickUpAddress = bcmAfsOrder?.pickUpAddress.replace(emojiRegex, '')
    }
    command.setText("取件地址：" + pickUpAddress);
    command.setPrint();
    command.setPrintAndFeedRow(1);

    command.bold(0);
    command.setFontSize(DEFAULT_FONT_SIZE);

    if (!type || type == '顾客联') {
        //打印二维码
        command.setSelectErrorCorrectionLevelForQRCode(51);
        command.setStoreQRCodeData(bcmAfsOrder?.thirdAfsOrderNo);
        command.setSelectJustification(1); //居中
        command.setSelectSizeOfModuleForQRCode(8); //大小
        command.setPrintQRCode();
        command.setPrint();

        command.setSelectJustification(1)//居中
        command.setText('售后单号：' + bcmAfsOrder.thirdAfsOrderNo);
        command.setPrint();
    }

    command.setPrintAndFeedRow(2);

    command.setText('-------------分割线-------------');
    command.setPrint();
    command.setPrintAndFeedRow(2);
    return command.getData();
}

/**
 * 获取订单打印指令
 * @param bcmAfsOrder 售后单对象
 * @param type 打印联类型：顾客联、商家联
 * @returns {object}
 */
const printAfsOrderCancelFormatCmd = function (bcmAfsOrder, type) {
    command.bold(1); //加粗
    command.setFontSize(MEDIUM_FONT_SIZE);
    command.setSelectJustification(1);
    command.setText(getPrintTitle(type));
    command.setPrint();
    command.setPrintAndFeedRow(1);
    const chnlName = getBcmDictItem('chnlType', bcmAfsOrder?.chnlType).text;
    command.setFontSize(LARGE_FONT_SIZE);
    command.bold(1); //加粗
    command.setSelectJustification(1)//居中
    command.setText(chnlName + (!!bcmAfsOrder?.thirdOrderIndex ? '#' + bcmAfsOrder?.thirdOrderIndex : ''));
    command.setPrint();
    command.bold(0);
    command.setFontSize(DEFAULT_FONT_SIZE);
    command.setSelectJustification(0)//居左

    command.setText('--------------------------------');
    command.setPrint();

    command.setText('门店名称：' + bcmAfsOrder?.storeName);
    command.setPrint();

    command.setText('发起时间：' + bcmAfsOrder?.sponsorTime);
    command.setPrint();

    command.setText('原订单号：' + bcmAfsOrder?.thirdOrderNo);
    command.setPrint();

    command.setText('售后单号：' + bcmAfsOrder?.thirdAfsOrderNo);
    command.setPrint();

    let afsReason = bcmAfsOrder?.afsReason;
    if (emojiRegex.test(bcmAfsOrder?.afsReason)) {
        afsReason = bcmAfsOrder?.afsReason.replace(emojiRegex, '')
    }
    command.bold(1);
    command.setFontSize(MEDIUM_FONT_SIZE);
    command.setText('原因：' + afsReason);
    command.setPrint();
    command.bold(0);
    command.setFontSize(DEFAULT_FONT_SIZE);

    command.setPrintAndFeedRow(2);
    command.setText('-------------分割线-------------');
    command.setPrintAndFeedRow(2);
    command.setPrint();
    return command.getData();
}


/**
 * 获取订单打印指令
 * @param bcmOrder 拣货任务
 * @param type 打印联类型：顾客联、商家联
 * @returns {object}
 */
const getPickTaskFormatCmd = function (bcmPickTask, type) {
    command.setFontSize(LARGE_FONT_SIZE);
    command.bold(1); //加粗
    command.setSelectJustification(1)//居中
    command.setText("拣货任务");
    command.setPrint();
    command.bold(0);
    command.setFontSize(DEFAULT_FONT_SIZE);
    command.setSelectJustification(0)//居左

    command.setText('--------------------------------');
    command.setPrint();

    command.setText('任务单号：' + bcmPickTask.pickTaskNo);
    command.setPrint();

    command.setText('门店：' + (bcmPickTask.storeCode ? bcmPickTask.storeCode : '-'));
    command.setPrint();

    command.setText('区域：' + (bcmPickTask.areaName ? bcmPickTask.areaName : '-'));
    command.setPrint();

    command.setText('拣货截止：' + (bcmPickTask.expectPickupTime ? bcmPickTask.expectPickupTime : '-'));
    command.setPrint();

    command.setText('最早配送：' + (bcmPickTask.expectDeliveryStartTime ? bcmPickTask.expectDeliveryStartTime : '-'));
    command.setPrint();

    command.setText('最晚配送：' + (bcmPickTask.expectDeliveryEndTime ? bcmPickTask.expectDeliveryEndTime : '-'));
    command.setPrint();
    command.setText('涉及订单' + bcmPickTask.orderNum + '个 商品' + bcmPickTask.goodsWeight + '件 重量' + 'kg');
    command.setPrint();

    command.setText('--------------------------------');
    command.setPrint();

    command.setText('商品名称        应拣数量');
    command.setPrint();

    command.setText('--------------------------------');
    command.setPrint();

    bcmPickTask.bcmPickTaskDetailList?.map((goods, index) => {
        let goodsName = goods.goodsName;
        if (emojiRegex.test(goodsName)) {
            goodsName = goods.goodsName.replace(emojiRegex, '')
        }
        command.bold(1);
        command.setFontSize(MEDIUM_FONT_SIZE);
        command.setText((index + 1) + '.' + goodsName);
        command.setPrint();

        command.setSelectJustification(2);   //居右
        command.setText('X' + goods.goodsNum);
        command.setPrint();

        command.bold(0);
        command.setFontSize(DEFAULT_FONT_SIZE);
        command.setSelectJustification(0); //局左
        command.setText('商品编码：' + goods.goodsCode);
        command.setPrint();

        command.setText('商品条码：' + goods.goodsBarcode);
        command.setPrint();
        command.setText('库位：' + (goods.locationCode ? goods.locationCode : '-'));
        command.setPrint();
    })
    command.setText('--------------------------------');
    command.setPrint();
    if (bcmPickTask?.pickerUserNo || bcmPickTask?.pickerName) {
        command.setText('拣货员：[' + bcmPickTask.pickerUserNo + ']' + bcmPickTask.pickerName);
        command.setPrint();
    }

    command.setPrintAndFeedRow(2);
    command.setText('-------------分割线-------------');
    command.setPrintAndFeedRow(2);
    command.setPrint();
    return command.getData();
}

/**
 * 连接打印机
 * @param  {
* @param  v 订单对象
* @param  type = 'order/afs
* }
*/
const handleBLEdevicess = ({
    v,
    type,
    reset = undefined
}) => {
    return new Promise((resolve, reject) => {
        const mainStore = useMainStore();
        const enjoyServiceIp = mainStore.enjoyServiceIp;
        const printerStore = usePrinterStore();
        const { bluetoothPrinter, printTimes } = storeToRefs(printerStore);
        if (enjoyServiceIp && enjoyServiceIp.EnjoyBCM) {
            function skipFunc(content = '打印失败，是否跳过打印流程进行后续操作？') {
                uni.showModal({
                    title: '提示',
                    content: content,
                    showCancel: true,
                    mask: true,
                    success: (res) => {
                        if (res.confirm) {
                            reset?.skip()
                            resolve(true)
                        } else {
                            resolve(false)
                            reset?.skipCancel()
                        }
                    }
                })
            }
            if (!bluetoothPrinter.value?.deviceId) {
                console.log("当前未设置蓝牙打印机");
                skipFunc("当前未设置蓝牙打印机，是否跳过打印？")
                return;
            }

            let data = getPrintData(v, type, printTimes.value);
            console.log("BluetoothPrinter:checkAndPrint===>then,res", printTimes.value, bluetoothPrinter.value);
            BluetoothPrinter.setDevice(bluetoothPrinter.value).checkAndPrint(data).then(res => {
                console.log("BluetoothPrinter:checkAndPrint===>then,res", res);
                if (res.code == '0') {
                    resolve();
                }
            }).catch(res => {
                skipFunc(res?.msg);
                console.log("BluetoothPrinter:checkAndPrint===>catch,res", res);
                // reject(res);
            })
        }
    })
}
const getBLEMessage = function (code, message) {
    return ERROR_MESSAGE[code] ? ERROR_MESSAGE[code] : message ? message : "未知错误";
}

export {
    getPrintData,
    handleBLEdevicess,
    getBLEMessage
}